//
//  NetworkTools.swift
//  Weibo10
//
//  Created by zhangbaiqiang on 16/1/6.
//  Copyright © 2016年 itheima. All rights reserved.
// https://api.weibo.com/oauth2/authorize?client_id=2808002429&redirect_uri=http://www.baidu.com
//  2808002429
//  25947c517010a9bfeb00fb84e321ab4f
// 加载用户信息, 通过AccessToken 获取用户信息,使用token获取数据


import UIKit
import AFNetworking

/// HTTP 请求方法枚举
enum HMRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: 网络工具
class NetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    private let appKey = "1407267207"
    private let appSecret = "6b66590f29bad6e7e7dd4c7b0c4dfa50"
    private let redirectUrl = "http://www.baidu.com"
    
    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()
    
    // 单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    /// 返回 token 字典
    private var tokenDict: [String: AnyObject]? {
        // 判断 token 是否有效
        if let token = UserAccountViewModel.sharedViewModel.accessToken {
            
            return ["access_token": token]
        }
        
        return nil
    }
}

// MARK: - 微博数据相关方法
extension NetworkTools {
    
    /// 加载微博数据
    ///
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(finished: HMRequestCallBack) {
        
        // 1. 获取 token 字典
        guard let params = tokenDict else {
            
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
        
        // 2. 准备网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 3. 发起网络请求
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}

// MARK: - 用户相关方法
extension NetworkTools {
    
    /// 加载用户信息
    ///
    /// - parameter uid:         uid
    /// - parameter finished:    完成回调
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid: String, finished: HMRequestCallBack) {
        
        // 1. 获取 token 字典
        guard var params = tokenDict else {
            
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
        
        // 2. 处理网络参数
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        params["uid"] = uid
        
        request(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}

// MARK: - OAuth 相关方法
extension NetworkTools {
    
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    /// 加载 AccessToken
    func loadAccessToken(code: String, finished: HMRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
        // 测试返回的数据内容 - AFN 默认的响应格式是 JSON，会直接反序列化
        // 如果要确认数据格式的问题
        // 如果是 NSNumber，则没有引号！在做 KVC 指定属性类型非常重要！
        //        // 1> 设置相应数据格式是二进制的
        //        responseSerializer = AFHTTPResponseSerializer()
        //
        //        // 2> 发起网络请求
        //        POST(urlString, parameters: params, success: { (_, result) -> Void in
        //
        //            // 将二进制数据转换成字符串
        //            let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
        //
        //            print(json)
        //
        //            // {"access_token":"2.00ml8IrF6dP8NEb33e7215aeRhrcdB",
        //            // "remind_in":"157679999",
        //            // "expires_in":157679999,
        //            // "uid":"5365823342"}
        //
        //            }, failure: nil)
    }
}

// MARK: - 封装 AFN 网络方法
extension NetworkTools {
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    private func request(method: HMRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
        
        // 定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        }
        
        
        if method == HMRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
}

   